package subscriptions

import (
	"GoTY/api"
	"bufio"
	"encoding/json"
	"fmt"
	"log"
	"os"
)

func writeFile(userPath string, channel string) {
	file, err := os.OpenFile(userPath, os.O_WRONLY, 0755)
	if err != nil {
		log.Fatalf("failed opening file: %s", err)
	}
	defer file.Close()

	_, err = file.WriteString(channel + "\n")
	if err != nil {
		log.Fatalf("failed writing to file: %s", err)
	}
}

func UnmarshalChannel[T api.Config | []api.Subs](userPath string, Channel *T) {
	r, err := os.ReadFile(userPath)
	if err != nil {
		panic(err)
	}

	err = json.Unmarshal(r, &Channel)
	if err != nil {
		fmt.Println(err)
	}
}

func MarshalChannel(localChannel api.Config) []byte {
	subs, err := json.Marshal(localChannel)
	if err != nil {
		fmt.Println(err)
	}
	return subs
}

func readQuery() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	return scanner.Text()
}

func AppendSub(userPath string) {
	var localSubs, localConfig = []api.Subs{}, api.Config{}
	UnmarshalChannel(userPath+"/.config/GoTY/subs.json", &localSubs)
	UnmarshalChannel(userPath+"/.config/GoTY/subs.json", &localConfig)

	fmt.Println("Enter your channel name")
	channelName := readQuery()

	fmt.Println("Enter your channelId")
	channelId := readQuery()

	addSubs := api.Subs{Snippet: struct {
		ChannelID string "json:\"channelId\""
		Title     string "json:\"title\""
	}{
		ChannelID: channelId,
		Title:     channelName,
	}}

	localSubs = append(localSubs, addSubs)
	localConfig.Subscriptions = append(localConfig.Subscriptions, localSubs...)
	subs := MarshalChannel(localConfig)
	writeFile(userPath+"/.config/GoTY/subs.json", string(subs))
}

func ShowChannel(userPath string) ([]string, []string) {
	var title, chId, channelInfo = []string{}, []string{}, api.Config{}

	UnmarshalChannel(userPath+"/.config/GoTY/subs.json", &channelInfo)
	for i := 0; i < len(channelInfo.Subscriptions); i++ {
		title = append(title, channelInfo.Subscriptions[i].Snippet.Title)
		chId = append(chId, channelInfo.Subscriptions[i].Snippet.ChannelID)
	}

	return title, chId
}

func ImportSubscription(userPath string) {
	var path string
	var ytChannel, localChannel = []api.Subs{}, api.Config{}
	fmt.Println("Enter the full path to the json file")
	fmt.Scan(&path)

	UnmarshalChannel(path, &ytChannel)
	UnmarshalChannel(userPath+"/.config/GoTY/subs.json", &localChannel)

	localChannel.Subscriptions = append(localChannel.Subscriptions, ytChannel...)
	subs := MarshalChannel(localChannel)
	writeFile(userPath+"/.config/GoTY/subs.json", string(subs))
}
